﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServiceOperater.Helpers
{
    // 引入 System.Configuration.dll
    //对于那些可能多次用到的值其实应该缓存起来
    public static class ConfigHelper
    {
        public static String DbConnectStr
        {
            get
            {
                string dbConnectStr = string.Empty;
#if DEBUG

#else
                switch (DbType)
                {
                    case DbType.ORACLE:
                        dbConnectStr = GetAppSettingValueByKey("servicePath");
                        break;
                    case DbType.SQLSERVER:
                        dbConnectStr = GetAppSettingValueByKey("SqlServerDbConnectStr");
                        break;
                    default:
                        break;
                }
#endif
                return dbConnectStr;
            }

        }

        public static String ServiceFolderPath
        {
            get
            {
                return GetAppSettingValueByKey("servicePath");
            }

        }

        public static String MybatisFolderPath
        {
            get
            {
                return GetAppSettingValueByKey("mybatisPath");
            }

        }

        public static String FrontFolderPath
        {
            get
            {
                return GetAppSettingValueByKey("frontPath");
            }

        }

        public static String JavaFolderPath
        {
            get
            {
                return GetAppSettingValueByKey("javaPath");
            }
        }

        public static String TextEditorPath
        {
            get
            {
                var textEditorPath = GetAppSettingValueByKey("textEditor");
                if (String.IsNullOrWhiteSpace(textEditorPath) || (!System.IO.File.Exists(textEditorPath)))
                {
                    return "notepad";
                }
                return textEditorPath;
            }
        }

        public static void Save()
        {

            // https://stackoverflow.com/questions/4216809/configurationmanager-doesnt-save-settings
            //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);



            cache.Clear();
        }

        private static Dictionary<string, string> cache = new Dictionary<string, string>(10);
        static string GetAppSettingValueByKey(string key)
        {
            if (!cache.ContainsKey(key))
            {
                string val = System.Configuration.ConfigurationManager.AppSettings[key];
                cache.Add(key, val);
            }
            return cache[key];
        }
    }
}
